package com.pricl.biz.file.api.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.WebApplicationContext;

import com.pricl.biz.file.api.IFileHandler;
import com.pricl.biz.file.entity.FileInfo;
import com.pricl.frame.common.utils.Utils;
import com.pricl.frame.core.web.Helper;

public class DefaultFileHandler implements IFileHandler {

	@Override
	public FileInfo[] save(FileInfo ofile, InputStream in, long length) {
		String sdir = Helper.getProp("file.saveDir");
		if (sdir == null || sdir.isEmpty()) {
			ApplicationContext ac = Helper.getApplicationContext();
			if (ac != null && ac instanceof WebApplicationContext) {
				sdir = ((WebApplicationContext) ac).getServletContext().getRealPath("/");
			}
			if (sdir == null || sdir.isEmpty()) {
				sdir = System.getProperty("webapp.root");
			}
			if (sdir == null || sdir.isEmpty()) {
				throw new RuntimeException("没有指定上传路径");
			}
		}
		File dir = new File(String.format("%s%s", sdir, ofile.getPath()));
		if (!dir.isDirectory()) {
			dir.mkdirs();
		}
		// 存储文件方式为：文件ID+扩展名
		File file = new File(String.format("%s/%s", dir.getAbsolutePath(), ofile.getFileName()));
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(file);
			Utils.readToWrite(in, fos, length);
			fos.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		// TODO 文件转换处理接口，这里生成文件格式数据，由异步线程来处理文件的转换
		// TODO 尝试使用队列来处理
		return null;
	}

}
